import { native } from "cc";
import NativeClient, { NativeClientIns, NCAPIStructure } from "./NativeClient";

const CONFIG = {
	class_ios: 'Ad_MessageManager_dA',
	request_call: 'Ad_callNative_dAWithName:data:',

	class_creator: 'Ad_iOSClient_dA',
	response_call: 'Ad_response_dA'
}

/** 原生端行为模拟 */
class iOSClient extends NativeClientIns {
	private static receive_call_list: Array<(api: string, response: Awaited<NCAPIStructure<any, any>['response']>)=>void> = [];

	public callStaticMethod(api: string, request: NCAPIStructure<any, any>['request']){
		iOSClient.request(api, request);
	}

	public onReceiveMessage(callback: (api: string, response: Awaited<NCAPIStructure<any, any>['response']>)=>void){
		iOSClient.receive_call_list.push(callback);
	}

	private static request(api: string, request: NCAPIStructure<any, any>['request']){
		native.reflection.callStaticMethod(CONFIG.class_ios, CONFIG.request_call, api, JSON.stringify(request));
	}

	private static response(api: string, json_string: string){
		let response = JSON.parse(json_string) as Awaited<NCAPIStructure<any, any>['response']>;
		iOSClient.receive_call_list.forEach(callback=>callback(api, response));
	}
}

NativeClient.initClient(platform=>{
	if(platform=='ios'){
		Reflect.set(globalThis ?? window, CONFIG.class_creator, iOSClient);
		Reflect.set(iOSClient, CONFIG.response_call, Reflect.get(iOSClient, 'response'));
		return new iOSClient();
	}else{
		return void 0;
	}
});
